<script setup lang="ts">
import { h, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import { useSortable } from '@vben/hooks';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElMessage,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTooltip,
} from 'element-plus';

import {
  getSalesChannelApi,
  getSupplierSaleSummeryApi,
  getSuppliersListApi,
} from '#/api';
import CollapsibleCard from '#/components/collapsibleCard.vue';
import CurrentDateTime from '#/components/currentDateTime.vue';
import RaiseStatus from '#/components/raiseStatus.vue';
import {
  getCommonShortcuts,
  getUrlParam,
  mergeDataByLabel,
  updateURLParams,
} from '#/utils';
import { convertToSingleImageAndPrint } from '#/utils/convertAndSplitImage';

const { locale } = useI18n();
const shortcuts = ref(getCommonShortcuts());

watch(locale, () => {
  shortcuts.value = getCommonShortcuts();
});

const submitForm: any = reactive({
  timeRange: [], // 统计日期
  supplierType: true, // 供应商分组
  publisherType: '全部', // 供应商类型
  supplier: [], // 供应商
  salesChannel: [], // 销售渠道
  salesType: '全部', // 销售类型
});

const lastCollectDate = ref<any>(null);

const onSubmit = async () => {
  if (!submitForm.timeRange[0] || !submitForm.timeRange[1]) {
    ElMessage.warning('请选择统计日期！');
    return;
  }
  searchLoading.value = true;
  try {
    const params = {
      startDate: submitForm.timeRange[0],
      endDate: submitForm.timeRange[1],
      ispubgroup: submitForm.supplierType,
      publishernames: submitForm.supplier,
      channelnames: submitForm.salesChannel,
      saletype: submitForm.salesType === '全部' ? '' : submitForm.salesType,
      publishertype:
        submitForm.publisherType === '全部' ? '' : submitForm.publisherType,
    };
    const { nowData, lastData, systemLastDate } =
      await getSupplierSaleSummeryApi(params);
    lastCollectDate.value = systemLastDate;

    const md: any = mergeDataByLabel(nowData, lastData, 'publisherName');
    md.forEach((item: any) => {
      item.cSaleDiscount = `${
        Math.floor((+item.cSaleShiyang / +item.cSaleMayang) * 10_000) / 100
      }`;
      item.lSaleDiscount = `${
        Math.floor((+item.lSaleShiyang / +item.lSaleMayang) * 10_000) / 100
      }`;
      item.cPurchaseDiscount = `${
        Math.floor((+item.cPubCostMoney / +item.cSaleMayang) * 10_000) / 100
      }`;
      item.lPurchaseDiscount = `${
        Math.floor((+item.lPubCostMoney / +item.lSaleMayang) * 10_000) / 100
      }`;
      // 结算毛利 = 实洋 - 预估成本 - 快递 - 平台扣点
      item.cSaleSettlementProfit = `${
        item.cSaleShiyang -
        item.cPubSettMoney -
        item.cExpressMoney -
        item.cPlatformMoney
      }`;
      item.lSaleSettlementProfit = `${
        item.lSaleShiyang -
        item.lPubSettMoney -
        item.lExpressMoney -
        item.lPlatformMoney
      }`;
      item.cSettlementGrossProfitMargin = `${
        Math.floor(
          (+item.cSaleSettlementProfit / Number(item.cSaleShiyang)) * 10_000,
        ) / 100
      }`;
      item.lSettlementGrossProfitMargin = `${
        Math.floor(
          (+item.lSaleSettlementProfit / Number(item.lSaleShiyang)) * 10_000,
        ) / 100
      }`;
    });
    tableData.value = md;
    applyAutoSort();
    updateURLParams({
      _k: JSON.stringify(submitForm),
    });

    // 数据更新后重新初始化拖拽功能
    await nextTick();
    initTableHeaderDrag();
  } catch (error: any) {
    console.error(error);
  } finally {
    searchLoading.value = false;
  }
  // console.warn(tableData.value);
};

const tableRef = ref<any>(null);

const applyAutoSort = () => {
  const sortBy = getUrlParam('sortBy');
  const sortOrder = getUrlParam('sortOrder');

  if (sortBy && sortOrder) {
    // 设置降序排序
    const columnIndex = tableRef.value?.columns?.findIndex(
      (item: any) => item.property === sortBy,
    );
    const icon = tableRef.value?.$el?.querySelectorAll(`th i.${sortOrder}`)?.[
      columnIndex
    ];
    if (icon) {
      icon.click();
    }
    handleSortChange({ prop: sortBy, order: sortOrder });
  }
};

const transNullTarget = (target: any, fixed: boolean = false) => {
  if (!target || `${target}` === 'NaN') {
    return '—';
  }
  if (fixed) {
    return (+target).toFixed(2);
  }
  return target;
};

onMounted(() => {
  getSupplierType();
  getSalesChannelType();
  updateScreenSize();
  dealUrlParams();
  restoreColumnOrder(); // 恢复列顺序
  window.addEventListener('resize', updateScreenSize);
});

const dealUrlParams = () => {
  if (getUrlParam('_k')) {
    Object.assign(submitForm, JSON.parse(getUrlParam('_k') || '{}'));
    onSubmit();
  }
};

onUnmounted(() => {
  window.removeEventListener('resize', updateScreenSize);
});

const getSummary = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];

  // 需要汇总展示的字段列表
  const summaryFields = new Set([
    'ExpressMoney',
    'PlatformMoney',
    'PubCostMoney',
    'PubSettMoney',
    'PurchaseDiscount',
    'PzNum',
    'SaleDiscount',
    'SaleGrossProfit',
    'SaleGrossProfitMargin',
    'SaleMayang',
    'SaleNum',
    'SaleSettlementProfit',
    'SaleShiyang',
    'SalesProportion',
    'SettlementGrossProfitMargin',
  ]);

  columns.forEach((column: any, index: number) => {
    // eslint-disable-next-line unicorn/prefer-string-slice
    const property = column.property.substring(1, column.property.length);

    if (property?.includes('PublisherName')) {
      // 特殊处理 PublisherName 列（只显示标题）
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
        $t('views.common.totalCost'),
      ]);
    } else if (summaryFields.has(property)) {
      // 需要汇总的字段统一处理
      const _sum = getColumnSummery(data, property);
      sums[index] = h('div', {}, [
        h('div', { class: 'flex justify-end' }, _sum[0]),
        h(RaiseStatus, {
          // eslint-disable-next-line no-constant-binary-expression
          r1: Number(_sum?.[0]) ?? 0,
          // eslint-disable-next-line no-constant-binary-expression
          r2: Number(_sum?.[1]) ?? 0,
        }),
        h('div', { class: 'flex justify-end' }, _sum[1]),
      ]);
    } else {
      // 其他列留空
      sums[index] = '';
    }
  });

  return sums;
};

const getColumnSummery = (data: any, key: string) => {
  if (data.length === 0) {
    return [0, 0];
  }
  const ck = `c${key}`;
  const lk = `l${key}`;

  let sumC: any = 0;
  let sumL: any = 0;

  data.forEach((item: any) => {
    // 防止字段不存在或不是数字
    const valC = Number(item[ck]) || 0;
    const valL = Number(item[lk]) || 0;

    sumC += valC;
    sumL += valL;
  });
  if (!key.includes('Num')) {
    sumC = sumC.toFixed(2);
    sumL = sumL.toFixed(2);
  }
  return [sumC, sumL];
};

const getSupplierType = async () => {
  const { data } = await getSuppliersListApi();
  options.supplierOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};
const getSalesChannelType = async () => {
  const { data } = await getSalesChannelApi();
  options.salesChannelOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};

const options = reactive<any>({
  supplierOptions: [],
  salesChannelOptions: [],
  salesTypeOptions: [
    {
      label: '全部',
      value: '全部',
    },
    {
      label: '经销',
      value: '经销',
    },
    {
      label: '分销',
      value: '分销',
    },
  ],
});

const searchLoading = ref(false);

const tableData = ref<any>([]);

const collapsed = ref(false);

// 动态监听窗口尺寸变化
const updateScreenSize = () => {
  if (collapsed.value === true) {
    return;
  }
  collapsed.value = window.innerWidth <= 1024;
};

async function printSection() {
  const w = document
    .querySelector('#printContent3 .el-table__header')
    ?.getBoundingClientRect()?.width;
  await convertToSingleImageAndPrint('#printContent3', `${w}px`);
}

const router = useRouter();

const supplierClick = (publisherName: any) => {
  const query = {
    ...submitForm,
    publisherName,
    pageNo: 1,
    pageSize: 50,
  };
  router.push({
    path: '/report/supplierSalesDetail',
    query: {
      k: JSON.stringify(query),
    },
  });
};

// 在 script setup 中添加
const sortBy = ref('');
const sortOrder = ref('');

const handleSortChange = ({ prop, order }: { order: string; prop: string }) => {
  sortBy.value = prop;
  sortOrder.value = order;
  updateURLParams({
    sortBy: prop,
    sortOrder: order,
  });
  if (order) {
    // 对于供应商类型，按文本排序
    if (prop === 'cPublisherName') {
      tableData.value.sort((a: any, b: any) => {
        const aVal = a[prop] || '';
        const bVal = b[prop] || '';

        return order === 'ascending'
          ? aVal.localeCompare(bVal)
          : bVal.localeCompare(aVal);
      });
    } else {
      // 其他列按数字排序，使用 c 开头的字段
      const sortField = prop.startsWith('c') ? prop : `c${prop}`;
      tableData.value.sort((a: any, b: any) => {
        const aVal = Number(a[sortField]) || 0;
        const bVal = Number(b[sortField]) || 0;

        return order === 'ascending' ? aVal - bVal : bVal - aVal;
      });
    }
  }
};

// 列配置
const columnOrder = ref<
  Array<{
    label: string;
    minWidth?: string;
    prop: string;
    sortable: string;
    tooltip: string;
  }>
>([
  {
    prop: 'cPublisherName',
    label: '供应商',
    minWidth: '60',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cPzNum',
    label: '品种',
    minWidth: '60%',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cSaleNum',
    label: '册数',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cSaleMayang',
    label: '码洋',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cSaleShiyang',
    label: '实洋',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cSaleDiscount',
    label: '销折',
    sortable: 'custom',
    tooltip: '总实洋/总码洋*100',
  },
  {
    prop: 'cSalesProportion',
    label: '销售占比',
    sortable: 'custom',
    tooltip: '当前的销售实洋/总销售实洋',
  },
  {
    prop: 'cPubSettMoney',
    label: '预估成本',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cPubSettDiscount',
    label: '预估折扣',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cExpressMoney',
    label: '快递成本',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cPlatformMoney',
    label: '平台扣点',
    sortable: 'custom',
    tooltip: '',
  },
  {
    prop: 'cSaleSettlementProfit',
    label: '毛利',
    sortable: 'custom',
    tooltip: '实洋 - 预估成本 - 快递成本 - 平台扣点',
  },
  {
    prop: 'cSettlementGrossProfitMargin',
    label: '毛利率',
    sortable: 'custom',
    tooltip: '毛利/销售实洋*100',
  },
]);

// 拖拽相关
const sortableInstance = ref<any>(null);

// 初始化表格头部拖拽
const initTableHeaderDrag = async () => {
  await nextTick();

  // 销毁之前的实例
  if (sortableInstance.value) {
    sortableInstance.value.destroy();
    sortableInstance.value = null;
  }

  if (tableRef.value?.$el) {
    const headerRow = tableRef.value.$el.querySelector(
      '.el-table__header-wrapper .el-table__header thead tr',
    );

    if (headerRow) {
      try {
        const { initializeSortable } = useSortable(headerRow, {
          animation: 150,
          ghostClass: 'sortable-ghost',
          chosenClass: 'sortable-chosen',
          dragClass: 'sortable-drag',
          filter:
            '.el-table__column-resize-proxy, .el-table__fixed-right-patch', // 过滤掉调整列宽的代理元素
          onEnd: (evt: any) => {
            const { newIndex, oldIndex } = evt;
            if (
              newIndex !== oldIndex &&
              newIndex !== undefined &&
              oldIndex !== undefined
            ) {
              const movedColumn = columnOrder.value.splice(oldIndex, 1)[0];
              if (movedColumn) {
                columnOrder.value.splice(newIndex, 0, movedColumn);
                updateURLParams({
                  columnOrder: JSON.stringify(
                    columnOrder.value.map((col) => col.prop),
                  ),
                });
              }
            }
          },
        });

        sortableInstance.value = await initializeSortable();
      } catch (error) {
        console.warn('Failed to initialize table header drag:', error);
      }
    }
  }
};

// 从 URL 参数恢复列顺序
const restoreColumnOrder = () => {
  const savedOrder = getUrlParam('columnOrder');
  if (savedOrder) {
    try {
      const orderArray = JSON.parse(savedOrder);
      const orderedColumns: typeof columnOrder.value = [];
      const existingColumns = [...columnOrder.value];

      // 按照保存的顺序重新排列列
      orderArray.forEach((prop: string) => {
        const column = existingColumns.find((col) => col.prop === prop);
        if (column) {
          orderedColumns.push(column);
        }
      });

      // 添加未保存的列（如果有新增列）
      existingColumns.forEach((column) => {
        if (!orderArray.includes(column.prop)) {
          orderedColumns.push(column);
        }
      });

      columnOrder.value = orderedColumns;
    } catch (error) {
      console.warn('Failed to restore column order:', error);
    }
  }

  // 初始化表格头部拖拽
  initTableHeaderDrag();
};

// 监听表格数据变化，重新初始化拖拽功能
watch(
  tableData,
  async () => {
    await nextTick();
    initTableHeaderDrag();
  },
  { flush: 'post' },
);

onMounted(() => {
  getSupplierType();
  getSalesChannelType();
  updateScreenSize();
  dealUrlParams();
  restoreColumnOrder(); // 恢复列顺序
  window.addEventListener('resize', updateScreenSize);
});

onUnmounted(() => {
  window.removeEventListener('resize', updateScreenSize);
  if (sortableInstance.value) {
    sortableInstance.value.destroy();
  }
});
</script>

<template>
  <!-- 使用 mx-auto 实现左右外边距自动，justify-center 让子元素水平居中 -->
  <div
    class="relative mx-auto flex items-center justify-center space-x-8"
    style="height: calc(100vh - 88px)"
  >
    <!-- 表单区域，隐藏时使用 v-show + transition -->
    <CollapsibleCard name="fade">
      <ElForm :model="submitForm" label-position="top" @keyup.enter="onSubmit">
        <ElFormItem :label="$t('views.common.collectDate')">
          <ElDatePicker
            v-model="submitForm.timeRange"
            type="daterange"
            date-format="yyyy-MM-DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('views.common.startDate')"
            :end-placeholder="$t('views.common.endDate')"
            :shortcuts="shortcuts"
          />
        </ElFormItem>
        <ElFormItem :label="$t('views.common.supplierType')">
          <ElSelect
            v-model="submitForm.publisherType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption label="全部" value="全部" />
            <ElOption label="新书" value="新书" />
            <ElOption label="特价" value="特价" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="供应商分组">
          <ElSelect
            v-model="submitForm.supplierType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption label="按大社" :value="true" />
            <ElOption label="按小社" :value="false" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.supplier')">
          <ElSelect
            v-model="submitForm.supplier"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesChannel')">
          <ElSelect
            v-model="submitForm.salesChannel"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesChannelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesType')">
          <ElSelect
            v-model="submitForm.salesType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <div class="flex w-full justify-center">
            <ElButton type="primary" @click="onSubmit">
              {{ $t('views.common.filter') }}
            </ElButton>
            <ElButton @click="printSection"> 打印 </ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </CollapsibleCard>

    <ElCard class="!ml-1 h-full flex-1 !overflow-auto" id="printContent3">
      <h2 class="my-2 flex items-center justify-center text-base font-bold">
        {{ `${$t('views.report.salesSummaryTitle')}` }}
      </h2>
      <div class="mb-2 flex justify-between text-xs">
        <div class="mr-4 flex justify-end">
          {{ $t('views.report.salesSummaryDesc') }}
        </div>
        <div class="flex justify-end">
          <div class="mr-4">最后数据时间：{{ lastCollectDate }}</div>
          <div class="mr-4">
            {{ $t('views.common.statisticalDate') }}：<span
              v-if="submitForm.timeRange[0] && submitForm.timeRange[1]"
            >
              {{ `${submitForm.timeRange[0]}` }} -
              {{ `${submitForm.timeRange[1]}` }}
            </span>
          </div>
          <CurrentDateTime />
        </div>
      </div>

      <!-- 拖拽提示 -->
      <div class="mb-2 text-center text-xs text-gray-500">
        💡 提示：可以直接拖拽表格头部来调整列顺序
      </div>

      <ElTable
        :data="tableData"
        border
        ref="tableRef"
        v-loading="searchLoading"
        :summary-method="getSummary"
        show-summary
        @sort-change="handleSortChange"
      >
        <ElTableColumn
          v-for="column in columnOrder"
          :key="column.prop"
          header-align="center"
          :prop="column.prop"
          :label="
            column.label.startsWith('views.') ? $t(column.label) : column.label
          "
          :min-width="column.minWidth"
          :sortable="column.sortable"
        >
          <template #header v-if="column.tooltip">
            <span>
              <ElTooltip class="item" effect="dark" placement="top-start">
                <span class="cursor-pointer">
                  {{ column.label }}
                </span>
                <template #content>
                  <div style="width: auto">{{ column.tooltip }}</div>
                </template>
              </ElTooltip>
            </span>
          </template>

          <template #default="scope">
            <!-- 供应商名称列 -->
            <template v-if="column.prop === 'cPublisherName'">
              <div
                class="text-align-right hover-supplier cursor-pointer !justify-start"
                @click="supplierClick(scope.row.cPublisherName)"
              >
                {{ transNullTarget(scope.row.cPublisherName) }}
              </div>
            </template>

            <!-- 其他列的统一模板 -->
            <template v-else>
              <div class="text-align-right">
                {{
                  transNullTarget(
                    scope.row[column.prop],
                    !column.prop.includes('Num'),
                  )
                }}
              </div>
              <RaiseStatus
                :r1="+scope.row[column.prop]"
                :r2="+scope.row[column.prop.replace('c', 'l')]"
              />
              <div class="text-align-right">
                {{
                  transNullTarget(
                    scope.row[column.prop.replace('c', 'l')],
                    !column.prop.includes('Num'),
                  )
                }}
              </div>
            </template>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
  </div>
</template>

<style scoped>
.text-align-right {
  @apply flex flex-wrap items-center justify-end break-words;
}

:deep(.el-table .cell) {
  padding: 0 8px !important;
}

.hover-supplier:hover {
  color: hsl(var(--primary, 210 100% 50%));
  text-decoration: underline;
  text-underline-offset: 2px; /* 设置下划线距离文字的距离 */
}

/* 表格头部拖拽样式 */
:deep(.el-table__header-wrapper .el-table__header thead tr) {
  cursor: grab;
}

:deep(.el-table__header-wrapper .el-table__header thead tr:active) {
  cursor: grabbing;
}

:deep(.el-table__header-wrapper .el-table__header th) {
  cursor: grab;
  user-select: none;
}

:deep(.el-table__header-wrapper .el-table__header th:active) {
  cursor: grabbing;
}

/* 拖拽相关样式 */
.sortable-ghost {
  background: #f0f0f0 !important;
  opacity: 0.5;
}

.sortable-chosen {
  background: #e6f7ff !important;
  border-color: #1890ff !important;
}

.sortable-drag {
  z-index: 1000;
  box-shadow: 0 4px 8px rgb(0 0 0 / 10%);
  opacity: 0.8;
  transform: rotate(2deg);
}

/* 拖拽时的表格头部样式 */
:deep(.el-table__header-wrapper .el-table__header.sortable-chosen) {
  background: #e6f7ff;
}

:deep(.el-table__header-wrapper .el-table__header.sortable-ghost) {
  background: #f0f0f0;
  opacity: 0.5;
}
</style>
